/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <devmon/driver_abi.h>
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <ios>
#include <test_utilities/test_base.h>

#include "../../../drivers/bus/i2c/i2c.h"
#include "../../../drivers/chip/powermeter/ina.h"
#include "../../../drivers/internal/hasdef.h"
#include "../../test_utils/root_object.h"

using namespace dev;
using namespace devmon;

namespace drivers {
namespace chip {
namespace ina_test {

class ina_test_service : public mc::engine::service {
public:
    ina_test_service(const std::string& name) : mc::engine::service(name) {
    }
};

class InaAbiTest : public mc::test::TestWithEngine {
public:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        // 动态创建服务实例，避免全局静态初始化导致的析构顺序问题
        m_test_service = mc::make_shared<ina_test_service>("bmc.kepler.test_ina");
        m_test_service->init();
        m_test_service->start();

        // 创建根对象
        m_root_object = root_object::create_root_object(m_test_service.get());

        load_driver();
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_root_object.reset();

        // 清理设备容器，避免引用已关闭的动态库
        m_devices.clear();
        m_i2c_devices.clear();

        // 不手动dlclose，避免静态对象析构时访问已卸载的动态库导致SIGSEGV
        // 让系统在程序退出时自动卸载动态库
        m_test_service.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    void TearDown() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    static void load_driver();

    // 创建并初始化总线驱动
    std::shared_ptr<device_driver_t> create_bus_driver(const std::string& driver_name);

    mc::dict create_test_connector(uint8_t system_id = 1, uint8_t position = 1, uint8_t slot = 1);

    // 创建总线CSR对象
    mc::dict create_bus_csr_object(uint8_t bus_id, uint32_t bus_speed, uint8_t bus_mode,
                                   uint8_t bus_slave_addr, bool bus_use_smbus);

    // 创建INA芯片CSR对象
    mc::mutable_dict create_ina_csr_object(
        uint32_t address, uint8_t offset_width, uint8_t address_width, uint32_t write_timeout,
        uint32_t read_timeout, uint8_t rw_block_size, uint8_t write_interval, uint8_t read_interval,
        uint8_t write_retry, uint8_t read_retry, uint32_t config_reg, uint32_t calibration_reg,
        const std::string& chip_model, uint32_t power_multiplier, uint32_t power_divisor);

    static mc::shared_ptr<ina_test_service>                                  m_test_service;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_devices;
    static void*                                                             m_driver_handle;
    static void*                                                             m_i2c_driver_handle;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_i2c_devices;
    static root_object_ptr                                                   m_root_object;
};

} // namespace ina_test
} // namespace chip
} // namespace drivers

// 静态变量定义
using namespace drivers::chip::ina_test;

mc::shared_ptr<ina_test_service> InaAbiTest::m_test_service;

std::unordered_map<std::string, std::shared_ptr<device_driver_t>> InaAbiTest::m_devices;

void* InaAbiTest::m_driver_handle     = nullptr;
void* InaAbiTest::m_i2c_driver_handle = nullptr;

std::unordered_map<std::string, std::shared_ptr<device_driver_t>> InaAbiTest::m_i2c_devices;

root_object_ptr InaAbiTest::m_root_object;

// 方法实现
void InaAbiTest::load_driver() {
    // 加载INA驱动
    m_driver_handle = dlopen("./opt/bmc/drivers/libIna.so", RTLD_LAZY);
    if (m_driver_handle == nullptr) {
        MC_THROW(mc::system_exception, "Failed to load Ina driver: ${error}", ("error", dlerror()));
    }
    register_device_driver_func func = reinterpret_cast<register_device_driver_func>(
        dlsym(m_driver_handle, "register_device_driver"));
    MC_ASSERT_THROW(func, mc::bad_function_call_exception,
                    "Failed to get register_device_driver function: ${error}",
                    ("error", dlerror()));

    device_driver_t* devices       = nullptr;
    uint8_t          devices_count = 0;
    status_t         ret           = func(&devices, &devices_count);
    MC_ASSERT_THROW(ret == STATUS_OK, mc::bad_function_call_exception,
                    "Failed to get device driver manager: ${error}", ("error", ret));

    m_devices.clear();
    m_devices.reserve(devices_count);
    for (uint8_t i = 0; i < devices_count; i++) {
        auto device_driver = std::make_shared<device_driver_t>(devices[i]);
        m_devices.emplace(device_driver->device_name, device_driver);
    }

    // 加载I2C驱动
    m_i2c_driver_handle = dlopen("./opt/bmc/drivers/libI2c.so", RTLD_LAZY);
    if (m_i2c_driver_handle == nullptr) {
        MC_THROW(mc::system_exception, "Failed to load I2c driver: ${error}", ("error", dlerror()));
    }
    register_device_driver_func i2c_func = reinterpret_cast<register_device_driver_func>(
        dlsym(m_i2c_driver_handle, "register_device_driver"));
    MC_ASSERT_THROW(i2c_func, mc::bad_function_call_exception,
                    "Failed to get I2c register_device_driver function: ${error}",
                    ("error", dlerror()));

    device_driver_t* i2c_devices       = nullptr;
    uint8_t          i2c_devices_count = 0;
    status_t         i2c_ret           = i2c_func(&i2c_devices, &i2c_devices_count);
    MC_ASSERT_THROW(i2c_ret == STATUS_OK, mc::bad_function_call_exception,
                    "Failed to get I2c device driver manager: ${error}", ("error", i2c_ret));

    m_i2c_devices.clear();
    m_i2c_devices.reserve(i2c_devices_count);
    for (uint8_t i = 0; i < i2c_devices_count; i++) {
        auto device_driver = std::make_shared<device_driver_t>(i2c_devices[i]);
        m_i2c_devices.emplace(device_driver->device_name, device_driver);
    }
}

std::shared_ptr<device_driver_t> InaAbiTest::create_bus_driver(const std::string& driver_name) {
    if (driver_name == "I2c") {
        auto it = m_i2c_devices.find("I2c");
        if (it != m_i2c_devices.end()) {
            return it->second;
        }
    }
    return nullptr;
}

mc::dict InaAbiTest::create_test_connector(uint8_t system_id, uint8_t position, uint8_t slot) {
    return mc::dict{{"SystemId", system_id}, {"Position", position}, {"Slot", slot}};
}

mc::dict InaAbiTest::create_bus_csr_object(uint8_t bus_id, uint32_t bus_speed, uint8_t bus_mode,
                                           uint8_t bus_slave_addr, bool bus_use_smbus) {
    return mc::dict{{"Id", bus_id},
                    {"Speed", bus_speed},
                    {"Mode", bus_mode},
                    {"SlaveAddr", bus_slave_addr},
                    {"UseSmbus", bus_use_smbus}};
}

mc::mutable_dict InaAbiTest::create_ina_csr_object(
    uint32_t address, uint8_t offset_width, uint8_t address_width, uint32_t write_timeout,
    uint32_t read_timeout, uint8_t rw_block_size, uint8_t write_interval, uint8_t read_interval,
    uint8_t write_retry, uint8_t read_retry, uint32_t config_reg, uint32_t calibration_reg,
    const std::string& chip_model, uint32_t power_multiplier, uint32_t power_divisor) {
    mc::mutable_dict csr;
    csr["Address"]               = address;
    csr["OffsetWidth"]           = offset_width;
    csr["AddrWidth"]             = address_width;
    csr["WriteTmout"]            = write_timeout;
    csr["ReadTmout"]             = read_timeout;
    csr["RwBlockSize"]           = rw_block_size;
    csr["WriteInterval"]         = write_interval;
    csr["ReadInterval"]          = read_interval;
    csr["WriteRetryTimes"]       = write_retry;
    csr["ReadRetryTimes"]        = read_retry;
    csr["ConfigurationRegister"] = config_reg;
    csr["CalibrationRegister"]   = calibration_reg;
    csr["ChipModel"]             = chip_model;
    csr["PowerMultiplier"]       = power_multiplier;
    csr["PowerDivisor"]          = power_divisor;
    return csr;
}

namespace drivers {
namespace chip {
namespace ina_test {

// ========================= 驱动注册功能测试 =========================

TEST_F(InaAbiTest, register_device_driver_success) {
    EXPECT_EQ(m_devices.size(), 1);
    EXPECT_TRUE(m_devices.find("Ina") != m_devices.end());

    // 验证I2C驱动也正确加载
    EXPECT_EQ(m_i2c_devices.size(), 1);
    EXPECT_TRUE(m_i2c_devices.find("I2c") != m_i2c_devices.end());
}

TEST_F(InaAbiTest, device_driver_structure_validation) {
    for (const auto& [device_name, device_driver] : m_devices) {
        EXPECT_FALSE(std::string(device_driver->device_name).empty());
        EXPECT_TRUE(device_driver->ctor != nullptr);
        EXPECT_TRUE(device_driver->init != nullptr);
        EXPECT_TRUE(device_driver->start != nullptr);
        EXPECT_TRUE(device_driver->stop != nullptr);
    }
}

// ========================= INA设备创建测试 =========================
TEST_F(InaAbiTest, create_ina_success) {
    // 使用唯一object_name创建内部对象
    std::string      object_name = "test_ina_device_obj";
    mc::mutable_dict csr_object  = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                         0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]    = object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), object_name.c_str());
    ASSERT_TRUE(device != nullptr);

    // 设置父对象后再注册
    auto ina_obj = static_cast<dev::ina_object*>(device);
    ina_obj->set_parent(m_root_object.get());
    m_test_service->register_object(static_cast<mc::engine::object_impl*>(device));
}

TEST_F(InaAbiTest, create_ina_null_service) {
    std::string      object_name = "test_ina_null_service_obj";
    mc::mutable_dict csr_object  = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                         0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]    = object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(nullptr, object_name.c_str());
    EXPECT_EQ(device, nullptr);
}

TEST_F(InaAbiTest, create_ina_null_name) {
    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), nullptr);
    EXPECT_EQ(device, nullptr);
}

// ========================= INA设备初始化测试 =========================
TEST_F(InaAbiTest, init_ina_success) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_for_ina";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建ina内部对象
    std::string      ina_object_name = "test_ina_init_obj";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                        0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto     connector = create_test_connector(1, 1, 1);
    status_t ret       = device_driver->init(device, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_OK);

    // 设置父对象后再注册
    auto ina_obj = static_cast<dev::ina_object*>(device);
    ina_obj->set_parent(m_root_object.get());
    m_test_service->register_object(static_cast<mc::engine::object_impl*>(device));
}

TEST_F(InaAbiTest, init_ina_null_params) {
    std::string      object_name = "test_ina_null_params_obj";
    mc::mutable_dict csr_object  = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                         0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]    = object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);
    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    status_t ret = device_driver->init(device, nullptr, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(InaAbiTest, init_ina_null_device) {
    std::string      object_name = "test_ina_null_device_obj";
    mc::mutable_dict csr_object  = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                         0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]    = object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);
    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto     connector = create_test_connector(1, 1, 1);
    status_t ret       = device_driver->init(nullptr, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_ERROR);
}

// ========================= INA属性验证测试 =========================
TEST_F(InaAbiTest, ina_properties_validation) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_properties";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建ina内部对象
    std::string      ina_object_name = "test_ina_properties_obj";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 2, 1, 2000, 1500, 64, 100, 20, 5, 3,
                                                        0x5000, 0x3000, "Ina226", 2000, 200);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto     connector = create_test_connector(1, 1, 1);
    status_t ret       = device_driver->init(device, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_OK);

    auto ina_obj = static_cast<dev::ina_object*>(device);
    ina_obj->set_parent(m_root_object.get());
    m_test_service->register_object(ina_obj);

    // 验证基础芯片接口属性
    EXPECT_EQ(ina_obj->m_interface_chip.Address.get_value(), 0x81U);
    EXPECT_EQ(ina_obj->m_interface_chip.OffsetWidth.get_value(), 2U);
    EXPECT_EQ(ina_obj->m_interface_chip.AddrWidth.get_value(), 1U);
    EXPECT_EQ(ina_obj->m_interface_chip.WriteTmout.get_value(), 2000U);
    EXPECT_EQ(ina_obj->m_interface_chip.ReadTmout.get_value(), 1500U);
    EXPECT_EQ(ina_obj->m_interface_chip.RwBlockSize.get_value(), 64U);
    EXPECT_EQ(ina_obj->m_interface_chip.WriteInterval.get_value(), 100U);
    EXPECT_EQ(ina_obj->m_interface_chip.ReadInterval.get_value(), 20U);
    EXPECT_EQ(ina_obj->m_interface_chip.WriteRetryTimes.get_value(), 5U);
    EXPECT_EQ(ina_obj->m_interface_chip.ReadRetryTimes.get_value(), 3U);

    // 验证INA专有接口属性
    // ConfigurationRegister 和 CalibrationRegister 是普通成员变量，不是 property
    EXPECT_EQ(ina_obj->m_interface_ina.ConfigurationRegister, 0x5000U);
    EXPECT_EQ(ina_obj->m_interface_ina.CalibrationRegister, 0x3000U);
    EXPECT_EQ(ina_obj->m_interface_ina.ChipModel.get_value(), "Ina226");
    EXPECT_EQ(ina_obj->m_interface_ina.PowerMultiplier.get_value(), 2000U);
    EXPECT_EQ(ina_obj->m_interface_ina.PowerDivisor.get_value(), 200U);
}

TEST_F(InaAbiTest, ina_properties_different_chip_models) {
    // 测试不同的芯片型号
    std::vector<std::string> chip_models = {"Ina220", "Ina226", "Ina238"};

    for (const auto& chip_model : chip_models) {
        std::string      i2c_object_name = "test_i2c_" + chip_model;
        mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
        i2c_csr["object_name"]           = i2c_object_name;
        auto i2c_internal =
            dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
        ASSERT_TRUE(i2c_internal != nullptr);

        std::string      ina_object_name = "test_ina_" + chip_model;
        mc::mutable_dict csr_object      = create_ina_csr_object(
            0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3, 0x4000, 0x2000, chip_model, 1000, 100);
        csr_object["object_name"] = ina_object_name;
        auto ina_internal =
            dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
        ASSERT_TRUE(ina_internal != nullptr);

        auto device_driver = m_devices["Ina"];
        ASSERT_TRUE(device_driver != nullptr);
        auto device = device_driver->ctor(m_test_service.get(), ina_object_name.c_str());
        ASSERT_TRUE(device != nullptr);
        auto     connector = create_test_connector(1, 1, 1);
        status_t ret       = device_driver->init(device, &csr_object, &connector);
        EXPECT_EQ(ret, STATUS_OK);

        auto ina_obj = static_cast<dev::ina_object*>(device);
        EXPECT_EQ(ina_obj->m_interface_ina.ChipModel.get_value(), chip_model);
    }
}

// ========================= INA设备启动停止测试 =========================
TEST_F(InaAbiTest, ina_start_stop) {
    std::string      i2c_object_name = "test_i2c_start_stop";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    std::string      ina_object_name = "test_ina_start_stop";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                        0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto device_driver = m_devices["Ina"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto     connector = create_test_connector(1, 1, 1);
    status_t ret       = device_driver->init(device, &csr_object, &connector);
    EXPECT_EQ(ret, STATUS_OK);

    // 测试启动
    ret = device_driver->start(device);
    EXPECT_EQ(ret, STATUS_OK);

    // 测试停止
    ret = device_driver->stop(device);
    EXPECT_EQ(ret, STATUS_OK);
}

// ========================= INA功能函数测试 =========================
// 注意：只测试 chip_ina 重写的四个方法：bit_read, bit_write, block_read, block_write

TEST_F(InaAbiTest, block_io_read_write) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_rw";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建ina内部对象
    std::string      ina_object_name = "test_ina_rw_obj";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                        0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto ina_driver = m_devices["Ina"];
    ASSERT_TRUE(ina_driver != nullptr);
    auto ina_device = ina_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(ina_device != nullptr);
    auto ina_obj = static_cast<dev::ina_object*>(ina_device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(m_test_service.get(), i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化INA芯片
    ret = ina_driver->init(ina_device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    ina_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(ina_obj);
    m_test_service->register_object(i2c_obj);

    // 设置连接关系
    ina_internal->set_left_bus(i2c_internal);
    ina_internal->set_host_bus(i2c_internal);

    // 设置底层I2C驱动的offset_width，使其与INA的OffsetWidth一致
    i2c_obj->m_interface_i2c.m_bus_i2c->m_i2c_drv->set_offset_width(1);

    // 测试块读写功能
    // Ina220 最大长度是 2 字节
    std::vector<uint8_t> write_data_vec = {0x01, 0x02};

    // 通过资源树对象的BlockIOWrite方法进行块写入
    ina_obj->m_interface_chip.BlockIOWrite(0x00, write_data_vec);

    // 通过资源树对象的BlockIORead方法进行块读取
    // 验证读取的数据与写入的数据一致（INA芯片会进行大小端转换，但转换是双向的）
    std::vector<uint8_t> read_buffer =
        ina_obj->m_interface_chip.BlockIORead(0x00, write_data_vec.size());
    ASSERT_EQ(read_buffer.size(), write_data_vec.size());
    ASSERT_EQ(read_buffer, write_data_vec) << "Block read/write data should match";
}

TEST_F(InaAbiTest, bit_io_read_write) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_bit_rw";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建ina内部对象
    std::string      ina_object_name = "test_ina_bit_rw_obj";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                        0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto ina_driver = m_devices["Ina"];
    ASSERT_TRUE(ina_driver != nullptr);
    auto ina_device = ina_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(ina_device != nullptr);
    auto ina_obj = static_cast<dev::ina_object*>(ina_device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(m_test_service.get(), i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化INA芯片
    ret = ina_driver->init(ina_device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    ina_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(ina_obj);
    m_test_service->register_object(i2c_obj);

    // 设置连接关系
    ina_internal->set_left_bus(i2c_internal);
    ina_internal->set_host_bus(i2c_internal);

    // 设置底层I2C驱动的offset_width，使其与INA的OffsetWidth一致
    i2c_obj->m_interface_i2c.m_bus_i2c->m_i2c_drv->set_offset_width(1);

    // 测试位读写功能
    uint32_t             test_offset = 0x00;
    uint8_t              test_length = 2;
    uint32_t             test_mask   = 0xFFFF;
    std::vector<uint8_t> write_data  = {0x12, 0x34};

    // 通过资源树对象的BitIOWrite方法进行位写入
    ina_obj->m_interface_chip.BitIOWrite(test_offset, test_length, test_mask, write_data);

    // 通过资源树对象的BitIORead方法进行位读取
    // 验证读取的数据与写入的数据一致（INA芯片会进行大小端转换，但转换是双向的）
    std::vector<uint8_t> read_buffer =
        ina_obj->m_interface_chip.BitIORead(test_offset, test_length, test_mask);
    ASSERT_EQ(read_buffer.size(), test_length);
    ASSERT_EQ(read_buffer, write_data) << "Bit read/write data should match";
}

TEST_F(InaAbiTest, io_functions_different_offsets) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_io_offsets";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x81, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建ina内部对象
    std::string      ina_object_name = "test_ina_io_offsets_obj";
    mc::mutable_dict csr_object = create_ina_csr_object(0x81, 1, 1, 1000, 1000, 32, 50, 10, 3, 3,
                                                        0x4000, 0x2000, "Ina220", 1000, 100);
    csr_object["object_name"]   = ina_object_name;
    auto ina_internal =
        dev::device_manager::get_instance().create_chip(ina_object_name, "Ina", csr_object);
    ASSERT_TRUE(ina_internal != nullptr);

    auto ina_driver = m_devices["Ina"];
    ASSERT_TRUE(ina_driver != nullptr);
    auto ina_device = ina_driver->ctor(m_test_service.get(), ina_object_name.c_str());
    ASSERT_TRUE(ina_device != nullptr);
    auto ina_obj = static_cast<dev::ina_object*>(ina_device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(m_test_service.get(), i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化INA芯片
    ret = ina_driver->init(ina_device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    ina_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(ina_obj);
    m_test_service->register_object(i2c_obj);

    // 设置连接关系
    ina_internal->set_left_bus(i2c_internal);
    ina_internal->set_host_bus(i2c_internal);

    // 设置底层I2C驱动的offset_width，使其与INA的OffsetWidth一致
    i2c_obj->m_interface_i2c.m_bus_i2c->m_i2c_drv->set_offset_width(1);

    // 测试不同偏移量的读写
    std::vector<uint32_t> test_offsets = {0x00, 0x01, 0x02, 0x05};

    for (uint32_t offset : test_offsets) {
        // Ina220 最大长度是 2 字节
        std::vector<uint8_t> write_data = {0x11, 0x22};

        try {
            // 测试BlockIOWrite
            ina_obj->m_interface_chip.BlockIOWrite(offset, write_data);

            // 测试BlockIORead
            // 验证读取的数据与写入的数据一致（INA芯片会进行大小端转换，但转换是双向的）
            std::vector<uint8_t> read_data =
                ina_obj->m_interface_chip.BlockIORead(offset, write_data.size());
            ASSERT_EQ(read_data.size(), write_data.size());
            ASSERT_EQ(read_data, write_data)
                << "Block read/write data should match at offset 0x" << std::hex << offset;
        } catch (const std::exception& e) {
            // 在测试环境中，某些偏移量可能不支持，这是正常的
            EXPECT_TRUE(true);
        }
    }
}

} // namespace ina_test
} // namespace chip
} // namespace drivers
